package cn.dankal.flyaudio.home

import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.SimpleItemAnimator
import android.view.View
import android.view.View.INVISIBLE
import android.widget.ImageView
import android.widget.TextView
import api.UserServiceFactory
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.DankalApplication
import cn.dankal.basiclib.base.BaseRvFragmentImp
import cn.dankal.basiclib.base.callback.DKCallBackObject
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewPresenter
import cn.dankal.basiclib.base.recyclerview.OnRvItemClickListener
import cn.dankal.basiclib.pojo.UserInfoBean
import cn.dankal.basiclib.protocol.LoginProtocol
import cn.dankal.basiclib.protocol.MainProtocol
import cn.dankal.basiclib.protocol.PersonalProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.widget.CommonDialog
import cn.dankal.business.pojo.CurrentBean
import cn.dankal.business.Constants
import cn.dankal.business.eventbus.MessageDriverHomeEvent
import cn.dankal.flyaudio.R
import cn.dankal.flyaudio.current.post.PublishActivity
import com.alibaba.android.arouter.launcher.ARouter
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragement_current.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 此刻
 */
class CurrentFragment : BaseRvFragmentImp<CurrentBean>(), CurrentPrsenter.PraiseCallback/*, ITitleBar */ {
    override fun onDetectCallback(message: String, position: Int) {
        ToastUtils.showShort(message)
    }

    lateinit var commonDialog: CommonDialog

    companion object {

        fun newInstance(): CurrentFragment {
            val fragment = CurrentFragment()
            return fragment
        }
    }

    private var isCreated = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isCreated = true
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (!isCreated) {
            return
        }

        if (isVisibleToUser) {
            obtainData()
        }
    }

    override fun initComponents() {
        super.initComponents()
        setTranslucent(activity, ll_action_title)
//        recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        (recyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

//        addTitleBar(this)
        view?.findViewById<ImageView>(R.id.iv_onback)?.visibility = INVISIBLE
        view?.findViewById<TextView>(R.id.tv_action)?.setOnClickListener {
            if (!DankalApplication.isLogin()) {
                ARouter.getInstance().build(LoginProtocol.LOGIN).navigation()
                return@setOnClickListener
            }

            UserServiceFactory.getUserInfo().subscribe(object : AbstractDialogSubscriber<UserInfoBean>(this) {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: UserInfoBean) {
                    if (t.isTourist()) {
                        val builder = CommonDialog.Builder(context)
                        builder.setTitle("您不是会员，暂时不能发布此刻，需要进行车主认证哦～")

                        builder.setNegativeButton("取消",
                                resources.getColor(R.color.color14)) {
                            commonDialog.dismiss()

                        }

                        builder.setPositiveButton("前去认证",
                                resources.getColor(R.color.colorPrimary)) {
                            ARouter.getInstance().build(PersonalProtocol.VERIFY).navigation()
                            commonDialog.dismiss()
                        }
                        commonDialog = builder.create()
                        commonDialog.show()
                    } else {
                        startActivity(Intent(context, PublishActivity::class.java))
                    }
                }
            })
        }
    }

    override fun onPraiseCallback(position: Int) {
        /* if (mAdapter.datas.size > position) {

             var likeCount: Int
             try {
                 likeCount = Integer.valueOf(mAdapter.datas[position].likeNumber)
             } catch (e: Exception) {
                 likeCount = 1
             }

             var tragetCurrent = mAdapter.datas.get(position)
             // 大于 0 表示为 已点赞
             if (tragetCurrent.isPraise > 0) {
                 mAdapter.datas.get(position).isPraise = 0
                 mAdapter.datas.get(position).likeNumber = (likeCount - 1).toString()
             } else {
                 mAdapter.datas.get(position).isPraise = 1
                 mAdapter.datas.get(position).likeNumber = (likeCount + 1).toString()
             }
             mAdapter.notifyItemChanged(position, "star")
         }*/
    }

    override fun getLayoutId(): Int {
        return R.layout.fragement_current
    }

    override fun getPresenter(): BaseRecyclerViewPresenter<CurrentBean>? {
        return CurrentPrsenter()
    }

    override fun getAdapter(): BaseRecyclerViewAdapter<CurrentBean>? {
        var currentAdapter = CurrentAdapter(DKCallBackObject {
            if (!DankalApplication.isLogin()) {
                ARouter.getInstance().build(LoginProtocol.LOGIN).navigation()
                return@DKCallBackObject
            }
//            (mPresenter as CurrentPrsenter).praise(it, DKCallBack {})
        })
        currentAdapter.setHasStableIds(true)
        currentAdapter.setOnParseListener(object : CurrentAdapter.OnPraiseListener {
            override fun deleteDate(uuids: Any, position: Int) {
                mAdapter.remove(position)
                var array: Array<String> = uuids as Array<String>
                (mPresenter as CurrentPrsenter).deleteInfo(array[0], position, this@CurrentFragment)
            }

            override fun praise(uuid: String, type: String, position: Int) {
                if (mAdapter.datas.size > position) {
                    var likeCount: Int
                    try {
                        likeCount = Integer.valueOf(mAdapter.datas[position].likeNumber)
                    } catch (e: Exception) {
                        likeCount = 1
                    }

                    var tragetCurrent = mAdapter.datas.get(position)
                    // 大于 0 表示为 已点赞
                    if (tragetCurrent.isPraise > 0) {
                        mAdapter.datas.get(position).isPraise = 0
                        mAdapter.datas.get(position).likeNumber = (likeCount - 1).toString()
                    } else {
                        mAdapter.datas.get(position).isPraise = 1
                        mAdapter.datas.get(position).likeNumber = (likeCount + 1).toString()
                    }
                    mAdapter.notifyItemChanged(position, "star")
                }
                ToastUtils.showShort("点赞成功")
                (mPresenter as CurrentPrsenter).praise(uuid, position, true, this@CurrentFragment)
            }

            override fun praiseCancel(uuid: String, type: String, position: Int) {
                ToastUtils.showShort("取消成功")
                if (mAdapter.datas.size > position) {
                    var likeCount: Int
                    try {
                        likeCount = Integer.valueOf(mAdapter.datas[position].likeNumber)
                    } catch (e: Exception) {
                        likeCount = 1
                    }

                    var tragetCurrent = mAdapter.datas.get(position)
                    // 大于 0 表示为 已点赞
                    if (tragetCurrent.isPraise > 0) {
                        mAdapter.datas.get(position).isPraise = 0
                        mAdapter.datas.get(position).likeNumber = (likeCount - 1).toString()
                    } else {
                        mAdapter.datas.get(position).isPraise = 1
                        mAdapter.datas.get(position).likeNumber = (likeCount + 1).toString()
                    }
                    mAdapter.notifyItemChanged(position, "star")
                }
                (mPresenter as CurrentPrsenter).praise(uuid, position, false, this@CurrentFragment)
            }
        })
        currentAdapter.setOnRvItemClickListener(object : OnRvItemClickListener<CurrentBean>() {
            override fun onItemClick(v: View?, position: Int, data: CurrentBean) {

                var isShowDelete = false
                if (data.userUuid.equals(DKUserManager.getUserInfo().userUuid)) {
                    isShowDelete = true
                } else {
                    isShowDelete = false
                }

                ARouter.getInstance().build(MainProtocol.CURRENT_DETAIL)
                        .withString(Constants.UUID, data.uuid)
                        .withBoolean("isShowDelete", isShowDelete)
                        .navigation()
            }
        })

        return currentAdapter
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onMessageEvent(event: MessageDriverHomeEvent) {
        if (mPresenter != null) {
            mPresenter.requestData(pageIndex.toString())
            mAdapter.notifyDataSetChanged()
        }
    }
}
